import os

from django.core.files.uploadedfile import InMemoryUploadedFile

from academic import settings
from authorshow.models import utils


def update_author_icon(id: str, icon_file: InMemoryUploadedFile):
    """
    更新 author 头像
    :param id: author id
    :param icon_file: 从表单上传的 author 头像文件
    :return: 成功：True 失败：False
    """
    author = utils.select_author(id=id).first()
    a_suffix = icon_file.name.split(sep='.', maxsplit=2)
    if (icon_file.size > settings.ICON_MAX_SIZE) or (len(a_suffix) != 2):
        return False
    else:
        icon_name = id + "." + a_suffix[1]
        icon_path = os.path.join(settings.ICON_ROOT, icon_name)
        with open(icon_path, 'wb') as f:
            for chunk in icon_file.chunks(chunk_size=1024):
                f.write(chunk)
        author.icon = os.path.join(settings.ICON_URL, icon_name)
        author.save()
        return True
